package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exceptionhandler.BusiException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;


import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;

public class JwtUtil {

    private static final Long TOKEN_TTL_TIME = 60 * 60 * 10 * 1000L;

    //    此处传递的字符串不能直接写"dy",要用该加密算法先加密
    //    密钥(对称加密)
    private static final SecretKey SIGN_KEY = Keys.hmacShaKeyFor("cb9e9921c4bf53e83e2b5a411eb3d17c35db7842".getBytes());


    public static String createToken(Long userId, String userName) {
        String token = Jwts.builder()
                .claim("userId", userId)
                .claim("userName", userName)
                .compressWith(CompressionCodecs.GZIP)
                .signWith(SIGN_KEY)
                .setSubject("lease-user-token")
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_TTL_TIME))
                .compact();
        return token;
    }

    public static Claims parseToken(String token) {
        try {
            JwtParser parser = Jwts.parserBuilder().setSigningKey(SIGN_KEY).build();
            Jws<Claims> claimsJws = parser.parseClaimsJws(token);
            return claimsJws.getBody();
        } catch (ExpiredJwtException e) {
            throw new BusiException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new BusiException(ResultCodeEnum.TOKEN_INVALID);
        }
    }
}
